package cn.dansj.handler.tasks;

import cn.dansj.annotation.MarkAsTask;
import cn.dansj.common.utils.json.DictMap;
import cn.dansj.common.request.RestTemplateUtils;
import cn.dansj.common.redis.RedisUtils;
import cn.dansj.common.context.ApplicationContextProvider;
import cn.dansj.common.utils.transfer.ArrayUtils;
import cn.dansj.common.utils.transfer.GetTime;
import cn.dansj.common.utils.transfer.RandomUtils;
import com.xxl.job.handler.Job;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@SuppressWarnings("all")
@MarkAsTask(id = 1)
public class GetOilPriceInfo extends Job {
    @Override
    public void execute() {
        final List<String> province = ArrayUtils.asList("安徽", "北京", "重庆", "福建", "甘肃", "广东", "广西", "贵州", "海南", "河北", "黑龙江", "河南", "湖北", "湖南", "江苏", "江西", "吉林", "辽宁", "内蒙古", "宁夏", "青海", "陕西", "上海", "山东", "山西", "四川", "天津", "西藏", "新疆", "云南", "浙江");

        String insertSql = "insert  into t_oil_price(sequence,province,t0,t89,t92,t95,t98,date) values(?,?,?,?,?,?,?,?)";
        List<Object[]> batchArgs = new ArrayList<>();
        String curDate = GetTime.stringTime("yyyy-MM-dd");
        for (String p : province) {
            String url = "https://www.mxnzp.com/api/oil/search?province=" + p + "&app_id=chretnsinicmefmj&app_secret=BN0fxR6f8buGw5OykrlOiUm6Rv2ywNcF";
            Map<?, ?> request = DictMap.parseObject(RestTemplateUtils.defaultInstance().get(url, Map.class).get("data"), Map.class);
            logger.info(DictMap.toJSONString(request));
            batchArgs.add(new Object[]{RandomUtils.sequence(), request.get("province"), request.get("t0"), request.get("t89"), request.get("t92"), request.get("t95"), request.get("t98"), curDate});
            try {
                Thread.sleep(1200);
            } catch (InterruptedException e) {
                break;
            }
        }
        int update = jdbcTemplate.update("delete from t_oil_price where date = ?", curDate);
        logger.info("delete rows:" + update);

        int[] ints = jdbcTemplate.batchUpdate(insertSql, batchArgs);
        logger.info("batch insert rows:" + ints.length);

        final RedisUtils redisUtils = ApplicationContextProvider.getBean(RedisUtils.class);
        final List<String> keys = redisUtils.keys("InterfaceResult@*");
        List<String> removeCache = new ArrayList<>();
        for (String name : keys) {
            final Object url = redisUtils.hget(name, "url");
            if ("/oil/search".equals(url)) {
                removeCache.add(name);
            }
        }

        final Long delete = redisUtils.delete(removeCache);

        logger.info("删除缓存{}条", delete);
    }
}
